<template>
  <div v-loading="loading">
    <div class="gl_mb_5 demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :span="4">
          <p>考官姓名</p>
          <el-input v-model="Api_GET_TrainExaminerExaminersTrainningIdQO.Name" placeholder="输入姓名查询" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="20" style="text-align:right">
          <el-button style="margin-top:27px" type="primary" size="mini" @click="getDataByName">查询</el-button>
          <el-button style="margin-top:27px" type="warning" size="mini" @click="resetData">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="timeset">
      <div style="line-height:28px;margin-right:5px;font-size:14px;">考官录入成绩时间设置：</div>
      <div v-if="entryTime.scoreRecordStartTime && editTime === false ">
        {{ entryTime.scoreRecordStartTime + ' - ' + entryTime.scoreRecordEndTime }}
        <el-button type="primary" size="mini" @click="editEntryTime">编辑</el-button>
      </div>
      <div v-else style="flex:1;">
        <div>
          <div style="display:inline-block;width:380px;">
            <el-date-picker
              v-model="datetimerange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 370px;"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="mini"
              @change="handleTimeChange"
            />
          </div>
          <el-button type="primary" size="mini" @click="confirmEntryTime">完成</el-button>
        </div>
        <div v-if="noTimeSet" class="timeReminder"><span class="innerDots" />若未完善考官录入成绩的时间，则在考官个人中心无法展示学员数据，且录入成绩</div>
      </div>
    </div>
    <div class="gl_margin_10 gl_clear">
      <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addExaminer">新增考试官</el-button>
    </div>
    <el-table size="mini" :data="examinerList" class="gl_table_noBorder mb_17" style="width: 100%" :index="table_index">
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="考官姓名" prop="name" />
      <el-table-column prop="number" label="考官编号" />
      <el-table-column prop="phoneNumber" label="手机号" />
      <el-table-column label="科目">
        <template slot-scope="{ row }">
          <div v-for="item in row.examinerSubjects" :key="item.subjectId">{{ item.subject.name }}</div>
        </template>
      </el-table-column>
      <el-table-column width="180" label="操作">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" @click="clickDelete(row)"><span class="gl_color_error">删除</span></el-button>
          <el-button size="mini" type="text" @click="clickEidt(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增考试官 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
      class="gl_dialog_TitleLine gl_dl_footer"
    >

      <div v-loading="editLoading" class="gl_px_20">
        <div v-if="!isEdit" class="gl_mb_15">
          <el-form ref="memberInquery" :model="Api_GET_EventsManagementRegisterByIdCardQO" :rules="memberInquery_rules">
            <el-form-item prop="name">
              <div class=" gl_fs_16 hg_30">姓名</div>
              <el-input v-model="Api_GET_EventsManagementRegisterByIdCardQO.name" type="text" placeholder="请输入" />
            </el-form-item>
            <el-form-item prop="idCardNumber">
              <div class=" gl_fs_16 hg_30">身份证号</div>
              <el-input v-model="Api_GET_EventsManagementRegisterByIdCardQO.idCardNumber" type="text" placeholder="请输入" />
            </el-form-item>
          </el-form>
          <div style="text-align:right;">
            <el-button type="primary" size="medium" @click="examinerInfoQuery()">查 询</el-button>
          </div>
          <div v-if="isInquery" class="gl_mt_15 gl_fs_16" style="height:22px;">查询结果</div>
          <div v-if="isInquery" class="queryResult">
            <div style="border-bottom: 1px solid rgba(0,0,0,0.15); margin-bottom:10px; padding: 10px;">
              <p class="gl_fs_16 gl_mb_10">{{ queryResult.name }}</p>
              <p class="gl_fs_14">身份证号 {{ queryResult.idCardNumber }}</p>
            </div>
            <div style="padding: 10px;">
              <el-checkbox-group v-model="addCheckList">
                <el-checkbox v-for="value in examList" :key="value.name" class="gl_mb_5" :label="value.name" style="width:100%" @change="editExamData(value.id)" />
              </el-checkbox-group>
            </div>
          </div>
          <div v-if="isInquery">
            <div class="gl_mt_20 gl_mb_5">
              <span class="gl_fs_16 hg_30">编号</span>
            </div>
            <div>
              <el-form ref="addNumber" :model="SiSTKWTrainExaminerInput" :rules="numberInquery_rules">
                <el-form-item prop="number">
                  <el-input v-model="SiSTKWTrainExaminerInput.number" maxlength="8" type="text" placeholder="请输入考官编号" />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <div v-else class="gl_mb_15">
          <div class="gl_mb_15">
            <div class=" gl_fs_16 hg_22">姓名</div>
            <el-input v-model="SiSTKWTrainExaminerInput.name" type="text" :disabled="true" />
          </div>
          <div class="gl_mb_15">
            <div class="gl_fs_16 hg_22">身份证号</div>
            <el-input v-model="SiSTKWTrainExaminerInput.idCardNumber" type="text" :disabled="true" />
          </div>
          <div>
            <div class="gl_fs_16 hg_22">科目</div>
            <div class="queryResult gl_px_10 gl_py_20">
              <el-checkbox-group v-model="editCheckList">
                <el-checkbox v-for="value in examList" :key="value.name" class="gl_mb_5" :label="value.name" style="width:100%" @change="editExamData(value.id)" /><br>
              </el-checkbox-group>
            </div>
          </div>
          <div class="gl_mt_20 hg_22 gl_fs_16">编号</div>
          <el-form ref="numberEdit" :model="SiSTKWTrainExaminerInput" :rules="numberInqueryEdit_rules">
            <el-form-item prop="number">
              <el-input v-model="SiSTKWTrainExaminerInput.number" type="text" maxlength="8" placeholder="请输入考官编号" />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="cancelDialog">取 消</el-button>
        <el-button size="medium" type="primary" @click="confirmDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <el-row style="text-align: right;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="Api_GET_TrainExaminerExaminersTrainningIdQO.MaxResultCount"
        :current-page="Api_GET_TrainExaminerExaminersTrainningIdQO.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>
  </div>
</template>

<script>
import {
  Api_GET_TrainExaminerExaminersTrainningIdQO,
  Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO,
  Api_GET_TrainSubjectQO,
  SiSTKWTrainExaminerInput } from '@/lib/form/train/swaggerForm';
import {
  api_GET_TrainExaminerExaminersTrainningId,
  api_POST_TrainExaminerSaveExaminerSettingTrainningId,
  api_GET_TrainSubject,
  api_PUT_TrainExaminerIdExaminer,
  api_POST_TrainExaminerExaminerTrainningId,
  api_DELETE_TrainExaminerIdExaminer,
  api_GET_TrainExaminerExaminerSettingTrainningId
} from '@/extend/api/trainswaggerApi/app';
import { Api_GET_EventsManagementRegisterByIdCardQO
} from '@/lib/form/game/swaggerForm';
import { api_GET_EventsManagementRegisterByIdCard
} from '@/extend/api/gameswaggerApi/app';
export default {
  data () {
    var validateIdCard = (rule, value, callback) => {
      const regex = new RegExp(/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/);
      if (!regex.test(value)) {
        return callback(new Error('请输入正确的身份证号'));
      } else {
        callback();
      }
    };
    var validateNum = (rule, value, callback) => {
      const regex = new RegExp(/^[A-Za-z0-9]{1,8}$/);
      if (!regex.test(value)) {
        return callback(new Error('请输入最高8位的大小写字母，数字'));
      } else {
        callback();
      }
    };
    return {
      Api_GET_TrainExaminerExaminersTrainningIdQO: new Api_GET_TrainExaminerExaminersTrainningIdQO(),
      trainningId: '',
      Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO: new Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO(),
      Api_GET_EventsManagementRegisterByIdCardQO: new Api_GET_EventsManagementRegisterByIdCardQO(),
      isEdit: false,
      SiSTKWTrainExaminerInput: new SiSTKWTrainExaminerInput(),
      Api_GET_TrainSubjectQO: new Api_GET_TrainSubjectQO(),
      examList: [],
      dialogTitle: '',
      dataId: '',
      loading: false,
      editLoading: false,
      memberInquery_rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        idCardNumber: [{ validator: validateIdCard, trigger: 'blur' }]
      },
      numberInquery_rules: {
        number: [{ validator: validateNum, trigger: 'blur' }]
      },
      numberInqueryEdit_rules: {
        number: [{ validator: validateNum, trigger: 'blur' }]
      },
      examinerList: [],
      isInquery: false,
      total: 1,
      datetimerange: [],
      dialogVisible: false,
      queryResult: {},
      addCheckList: [],
      editCheckList: [],
      entrytimeIsshow: true,
      entryTime: {},
      noTimeSet: false,
      editTime: false
    };
  },

  created () {
    this.trainningId = this.$router.app._route.params.id;
    this.getPageList();
    this.getEntryTime();
  },
  methods: {
    // 获取选中科目列表
    editExamData(id) {
      if (this.SiSTKWTrainExaminerInput.subjectIds.indexOf(id) === -1) {
        this.SiSTKWTrainExaminerInput.subjectIds.push(id);
      } else {
        this.SiSTKWTrainExaminerInput.subjectIds.splice(this.SiSTKWTrainExaminerInput.subjectIds.indexOf(id), 1);
      }
    },
    // 分页获取考官人员列表
    getPageList (page) {
      this.loading = true;
      this.Api_GET_TrainExaminerExaminersTrainningIdQO.IncludeTrainning = true;
      this.Api_GET_TrainExaminerExaminersTrainningIdQO.Page = page || 1;
      this.Api_GET_TrainExaminerExaminersTrainningIdQO.SkipCount = (this.Api_GET_TrainExaminerExaminersTrainningIdQO.Page - 1) * this.Api_GET_TrainExaminerExaminersTrainningIdQO.MaxResultCount;
      api_GET_TrainExaminerExaminersTrainningId(this.trainningId, this.Api_GET_TrainExaminerExaminersTrainningIdQO).then(res => {
        this.loading = false;
        this.total = res.totalCount;
        this.examinerList = res.items || [];
      }, error => {
        this.loading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    clickDelete (row) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_TrainExaminerIdExaminer(row.id).then(res => {
            this.getPageList();
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        })
        .catch(() => {
        });
    },
    // 获取培训科目列表
    getTrainSubject() {
      this.Api_GET_TrainSubjectQO.trainningId = this.trainningId;
      api_GET_TrainSubject(this.Api_GET_TrainSubjectQO).then(res => {
        this.examList = res.examSubjects;
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 编辑单条信息
    clickEidt (row) {
      this.editCheckList = [];
      this.isEdit = true;
      this.isInquery = false;
      this.dialogVisible = true;
      this.dialogTitle = '编辑考试官';
      this.dataId = row.id;
      this.SiSTKWTrainExaminerInput = new SiSTKWTrainExaminerInput();
      this.SiSTKWTrainExaminerInput.registerId = row.registerId;
      this.SiSTKWTrainExaminerInput.name = row.name;
      this.SiSTKWTrainExaminerInput.idCardNumber = row.idCardNumber;
      this.SiSTKWTrainExaminerInput.number = row.number;
      this.SiSTKWTrainExaminerInput.phoneNumber = row.phoneNumber;
      this.SiSTKWTrainExaminerInput.subjectIds = row.examinerSubjects.map(item => item.subjectId);
      this.editCheckList = row.examinerSubjects.map(item => item.subject.name);
      this.getTrainSubject();
    },
    // 分页
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.Api_GET_TrainExaminerExaminersTrainningIdQO.MaxResultCount = pagesize;
      this.getPageList();
    },
    table_index(index) {
      return (this.Api_GET_TrainExaminerExaminersTrainningIdQO.Page - 1) * this.Api_GET_TrainExaminerExaminersTrainningIdQO.MaxResultCount + index + 1;
    },
    handleTimeChange(time) {
      if (time) {
        this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordStartTime = time[0];
        this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordEndTime = time[1];
      } else {
        this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordStartTime = null;
        this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordEndTime = null;
      }
    },
    getDataByName() {
      this.getPageList();
    },
    resetData() {
      this.$set(this.Api_GET_TrainExaminerExaminersTrainningIdQO, 'Name', '');
      this.getPageList();
    },
    confirmEntryTime() {
      // this.entrytimeIsshow = !this.entrytimeIsshow;

      if (this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordStartTime === null || this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordEndTime === null) {
        this.$message({ type: 'warning', message: '请先选择成绩录入时间' });
        // this.entrytimeIsshow = !this.entrytimeIsshow;
        return;
      }
      api_POST_TrainExaminerSaveExaminerSettingTrainningId(this.trainningId, this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO).then(res => {
        this.editTime = false;
        this.datetimerange = [];
        this.$message({ type: 'success', message: '设置成功！' });
        this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO = new Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO();
        this.getEntryTime();
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    getEntryTime() {
      this.entryTime = {};
      this.datetimerange = [];
      api_GET_TrainExaminerExaminerSettingTrainningId(this.trainningId).then(res => {
        if (res) {
          this.noTimeSet = false;
          this.datetimerange.push(res.scoreRecordStartTime.replace('T', ' '));
          this.datetimerange.push(res.scoreRecordEndTime.replace('T', ' '));
          this.$set(this.entryTime, 'scoreRecordStartTime', res.scoreRecordStartTime.replace('-', '年').replace('-', '月').replace('T', '日 '));
          this.$set(this.entryTime, 'scoreRecordEndTime', res.scoreRecordEndTime.replace('-', '年').replace('-', '月').replace('T', '日 '));
        } else {
          this.noTimeSet = true;
        }
      }, error => {
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    editEntryTime() {
      // this.entrytimeIsshow = !this.entrytimeIsshow;
      this.editTime = true;
      this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordStartTime = this.datetimerange[0];
      this.Api_POST_TrainExaminerSaveExaminerSettingTrainningIdQO.scoreRecordEndTime = this.datetimerange[1];
      // this.getEntryTime();
    },
    // 新增考试官按钮
    addExaminer() {
      this.isEdit = false;
      this.dialogTitle = '新增考试官';
      this.SiSTKWTrainExaminerInput = new SiSTKWTrainExaminerInput();
      this.Api_GET_EventsManagementRegisterByIdCardQO = new Api_GET_EventsManagementRegisterByIdCardQO();
      this.dialogVisible = true;
      this.addCheckList = [];
      this.queryResult = {};
      this.getTrainSubject();
    },
    cancelDialog() {
      this.isInquery = false;
      this.dialogVisible = false;
    },
    // 执行新增或编辑
    confirmDialog() {
      if (!this.isEdit && !this.isInquery) {
        this.$message({ type: 'warning', message: '请先查询考官信息' });
        return;
      }
      if (!this.isEdit && JSON.stringify(this.queryResult) === '{}' && this.isInquery) {
        this.$message({ type: 'warning', message: '请先查询考官信息' });
        return;
      }
      if (this.SiSTKWTrainExaminerInput.subjectIds.length === 0) {
        this.$message({ type: 'warning', message: '请选择培训科目' });
        return;
      }
      if (this.SiSTKWTrainExaminerInput.number !== '') {
        const reg = new RegExp(/^[A-Za-z0-9]{1,8}$/);
        if (!reg.test(this.SiSTKWTrainExaminerInput.number)) {
          this.$message({ type: 'warning', message: '请输入最高8位的大小写字母，数字' });
          return;
        }
      }
      if (this.isEdit) {
        this.editLoading = true;
        api_PUT_TrainExaminerIdExaminer(this.dataId, this.SiSTKWTrainExaminerInput).then(res => {
          this.editLoading = false;
          this.$message({ type: 'success', message: '修改成功！' });
          this.getPageList();
          this.dialogVisible = false;
        }, error => {
          this.dialogVisible = false;
          this.editLoading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      } else {
        this.SiSTKWTrainExaminerInput.registerId = this.queryResult.registerId;
        this.SiSTKWTrainExaminerInput.phoneNumber = this.queryResult.phoneNumber;
        this.SiSTKWTrainExaminerInput.name = this.Api_GET_EventsManagementRegisterByIdCardQO.name;
        this.SiSTKWTrainExaminerInput.idCardNumber = this.Api_GET_EventsManagementRegisterByIdCardQO.idCardNumber;
        if (this.queryResult.idCardNumber === this.Api_GET_EventsManagementRegisterByIdCardQO.idCardNumber &&
        this.queryResult.name === this.Api_GET_EventsManagementRegisterByIdCardQO.name) {
          this.editLoading = true;
          api_POST_TrainExaminerExaminerTrainningId(this.trainningId, this.SiSTKWTrainExaminerInput).then(res => {
            this.editLoading = false;
            this.$message({ type: 'success', message: '添加成功！' });
            this.isInquery = false;
            this.getPageList();
            this.dialogVisible = false;
          }, error => {
            this.editLoading = false;
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        } else {
          this.$message({ type: 'warning', message: '请确认验证信息是否正确' });
        }
      }
    },
    // 查询用户是否注册
    examinerInfoQuery() {
      this.$set(this.queryResult, 'phoneNumber', '');
      this.$set(this.queryResult, 'registerId', '');
      this.addCheckList = [];
      if (this.Api_GET_EventsManagementRegisterByIdCardQO.name === '' || this.Api_GET_EventsManagementRegisterByIdCardQO.idCardNumber === '') {
        this.$message({ type: 'warning', message: '请输入验证信息' });
        return;
      }
      const regex = new RegExp(/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/);
      if (!regex.test(this.Api_GET_EventsManagementRegisterByIdCardQO.idCardNumber)) {
        return;
      }
      this.Api_GET_EventsManagementRegisterByIdCardQO.idCardCode = 'IdCard';
      this.Api_GET_EventsManagementRegisterByIdCardQO.IncludeRegisterType = true;
      this.Api_GET_EventsManagementRegisterByIdCardQO.IncludeGender = true;
      this.Api_GET_EventsManagementRegisterByIdCardQO.IncludeIdCardType = true;
      this.Api_GET_EventsManagementRegisterByIdCardQO.IncludeTags = true;
      this.Api_GET_EventsManagementRegisterByIdCardQO.IncludeDelegations = true;
      this.Api_GET_EventsManagementRegisterByIdCardQO.IncludeDelegationEntries = true;
      this.editLoading = true;
      api_GET_EventsManagementRegisterByIdCard(this.Api_GET_EventsManagementRegisterByIdCardQO).then(res => {
        this.editLoading = false;
        if (res) {
          this.isInquery = true;
          this.$set(this.queryResult, 'name', res.name);
          this.$set(this.queryResult, 'idCardNumber', res.idCardNumber);
          this.$set(this.queryResult, 'phoneNumber', res.phoneNumber);
          this.$set(this.queryResult, 'registerId', res.registerTags[0].registerId);
        } else {
          this.isInquery = false;
          this.$message({ type: 'warning', message: '未找到该用户' });
        }
      }, error => {
        this.editLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .mb_17 {
    margin-bottom: 17px;
  }
  .timeTitle {
    width: 140px;
    display: inline-block;
    height: 18px;
    font-size: 14px;
    line-height: 18px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 500;
    margin: 5px 0px 0px 5px;
  }
  .timeMessageCol {
    color: #ff4949;
  }
  .queryResult {
    width: 100%;
    border: 1px solid rgba(0,0,0,0.15);
    border-radius: 4px;
  }
  .hg_30 {
    height: 32px;
  }
  .hg_22 {
    height: 22px;
  }
  .timeReminder {
    margin-top: 5px;
    font-size: 14px;
    color: #DE1C1C;
    line-height: 18px;
    .innerDots {
      margin-right: 3px;
      display: inline-block;
      width:8px;
      height: 8px;
      background: #DE1C1C;
      border-radius: 50%;
    }
  }
  .timeset {
    display: flex;
    margin: 10px;
  }
</style>
